﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;

namespace Client.Forms
{
    public partial class Client : Form
    {
        ToolStripMenuItem zxgMenuItem;
        ToolStripMenuItem tempKFreqItem;
        ToolStripMenuItem tempKAdjItem;
        List<ToolStripMenuItem> kFreqItemList = new List<ToolStripMenuItem>();
        List<ToolStripMenuItem> kAdjItemList = new List<ToolStripMenuItem>();

        public Client()
        {
            InitializeComponent();
            InitClientForm();
        }

        private void InitClientForm()
        {
            ToolStripMenuItem scylMenuItem = new ToolStripMenuItem("市场一览");
            ToolStripMenuItem bkphMenuItem = new ToolStripMenuItem("板块排行");
            zxgMenuItem = new ToolStripMenuItem("自选分类");
            ToolStripMenuItem meMenuItem = new ToolStripMenuItem("我的");

            this.menuStrip1.SuspendLayout();
            this.menuStrip1.Items.AddRange(new ToolStripMenuItem[]{
                scylMenuItem,bkphMenuItem,zxgMenuItem,meMenuItem});
            //
            // scylMenuItem
            //
            scylMenuItem.Name = "scyl";
            CreateSCYLSubitem(scylMenuItem);
            //
            //  stockContextMenuStrip
            //
            TickviewToolStripMenuItem.Click += (s, e) =>
            {
                StockMenuFuncs.OpenTickView(hotInfo);
            };
            KviewToolStripMenuItem.Click += (s, e) =>
            {
                StockMenuFuncs.OpenKlineView(hotInfo);
            };
            addZXGToolStripMenuItem.Click += (s, e) =>
            {
                Managers.Manager.zxgM.AddZXG(Managers.Manager.hotStockInfo);
            };
            removeZXGToolStripMenuItem.Click += (s, e) =>
            {
                Managers.Manager.zxgM.removeZXG(Managers.Manager.hotStockInfo);
            };
            NewsToolStripMenuItem.Click += (s, e) =>
            {
                StockMenuFuncs.OpenNews(hotInfo);
            };
            generalInfomationToolStripMenuItem.Click += (s, e) =>
            {
                StockMenuFuncs.OpenGeneralInfomation();
            };
            quickAddToolStripMenuItem.Click += (s, e) =>
            {
                Managers.Manager.zxgM.AddStock(Managers.Manager.hotStockInfo.symbol);
            };
            kFreqItemList.AddRange(new ToolStripMenuItem[] { dayKToolStripMenuItem, weekKtoolStripMenuItem, monthKtoolStripMenuItem, m5KToolStripMenuItem, m30KToolStripMenuItem, m60KToolStripMenuItem });
            foreach(var i in kFreqItemList)
            {
                i.Click += KFreqItemToolStripMenuItem_click;
            }
            foreach(ToolStripMenuItem i in fqToolStripMenuItem.DropDown.Items)
            {
                i.Click += KAdjItemToolStripMenuItem_click;
            }
            //kAdjItemList.AddRange(new ToolStripMenuItem[] { qfqToolStripMenuItem, hfqToolStripMenuItem });
            //foreach(var i in kAdjItemList)
            //{
            //    i.Click += KAdjItemToolStripMenuItem_click;
            //}
            timeKToolStripMenuItem.Click += (s, e) =>
            {
                StockMenuFuncs.ChoiceKTime(hotInfo);
            };
            constituentToolStripMenuItem.Click += (s, e) =>
            {
                StockMenuFuncs.GetConstituentStocks(hotInfo);
            };
            //
            // bkphMenuItem
            //
            bkphMenuItem.Name = "bkphMenuItem";
            CreateBKPHSubitem(bkphMenuItem);
            //
            //zxgMenuItem
            //
            zxgMenuItem.Name = "zxgMenuItem";
            InitZXGMenu();
            //
            //  meMenuItem
            //
            //var settingMenuItem = new ToolStripMenuItem("设置");
            //settingMenuItem.AccessibleName = "设置子菜单";
            var voiceSettingToolStripItem = new ToolStripMenuItem("语音设置");
            voiceSettingToolStripItem.Click += (s, e) => new Forms.VoiceSettingForm().ShowDialog();
            //settingMenuItem.DropDown.Items.Add(voiceSettingToolStripItem);
            var beepSettingToolStripItem = new ToolStripMenuItem("音效设置");
            beepSettingToolStripItem.Click += (s, e) => new Forms.BeepTimeSettingForm().ShowDialog();
            //settingMenuItem.DropDown.Items.Add(beepSettingToolStripItem);
            var userPointMenuItem = new ToolStripMenuItem("积分查询");
            userPointMenuItem.Click += async (s, e) =>
             {
                 try
                 {
                     if (DataCenter.DataCenter.user.status > -1)
                     {
                         var str = await DataCenter.DataCenter.GetUserPoint();
                         JObject jo = JObject.Parse(str);
                         var msg = "您的订阅还有" + ((int)jo["balance"] / (int)jo["point_per_day"]) + "天。\r\n获得系统赠送" + (int)jo["gtimes"] + "次，总计" + ((int)jo["gtotal"] / (int)jo["point_per_day"]) + "天。\r\n\r\n";
                         DialogResult dr;
                         if ((int)jo["balance"] / (int)jo["point_per_day"] < 5)
                             dr = MessageBox.Show(msg+"为了不影响正常使用，请续期您的订阅。\r\n是否现在续期？", "订阅查询", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
                         else
                             dr = MessageBox.Show(msg+"是否现在续期您的订阅？", "订阅查询", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button2);
                         if (dr == DialogResult.Yes)
                             new TopUpForm(DataCenter.DataCenter.user.userId, false).ShowDialog();
                     }
                     else
                     {
                         string msg = "您还没有订阅" + MyConst.StaticString.APPNAME + "，或订阅已过期。请订阅" + MyConst.StaticString.APPNAME + "，享受畅快的操盘体验。\r\n\r\n是否现在订阅？";
                         var dr = MessageBox.Show(msg, "订阅查询", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
                         if (dr == DialogResult.Yes)
                             new TopUpForm(DataCenter.DataCenter.user.userId, false).ShowDialog();
                     }
                 }
                 catch (DataCenter.MyException.APIReturnException ex)
                 {
                     var l = ex.Message.Split('~');
                     if (l[0] == "1000")
                         Utility.ShowLoginAgain();
                     throw;
                 }
             };
            var manualMenuTripItem = new ToolStripMenuItem("新手入门");
            manualMenuTripItem.Click += (s, e) =>
            {
                string manualPath = System.IO.Path.Combine(Application.StartupPath, "manual");
                System.Console.WriteLine(manualPath);
                System.Diagnostics.Process.Start("explorer.exe", manualPath);
            };
            var createCardsMenuItem = new ToolStripMenuItem("生成卡密");
            createCardsMenuItem.Click += (s, e) =>
              {
                  var f = new Forms.CreateCardsForm();
                  f.Show();
              };
            meMenuItem.DropDown.Items.AddRange(new ToolStripMenuItem[] { userPointMenuItem, voiceSettingToolStripItem, beepSettingToolStripItem, manualMenuTripItem });
            if (DataCenter.DataCenter.user.status == 100)
                meMenuItem.DropDown.Items.Add(createCardsMenuItem);

            this.menuStrip1.ResumeLayout(true);

            Managers.Manager.clientForm = this;
        }

        void CreateSCYLSubitem(ToolStripMenuItem root)
        {
            ToolStripMenuItem ggyl = new ToolStripMenuItem("个股一览");
            ggyl.AccessibleDescription = "子菜单";

            ToolStripMenuItem zdb = new ToolStripMenuItem("涨跌榜");
            ToolStripMenuItem hsl = new ToolStripMenuItem("换手率Top10");
            ToolStripMenuItem zlzj = new ToolStripMenuItem("主力资金流入/流出");
            ToolStripMenuItem cje = new ToolStripMenuItem("成交量Top10");
            ToolStripMenuItem ddpx = new ToolStripMenuItem("大单频现Top10");


            zdb.Click += (s, e) =>
            {
                if (!DataCenter.DataCenter.HavePermission(DataCenter.MyConst.APINames.GGYL))
                {
                    StockMenuFuncs.AskTopUp();
                    return;
                }
                Managers.Manager.panelM.ClearPanels();
                var p = new Panels.ZFBPanel();
                Managers.Manager.panelM.AddPanel(p);
            };
            hsl.Click += (s, e) =>
             {
                 if (!DataCenter.DataCenter.HavePermission(DataCenter.MyConst.APINames.GGYL))
                 {
                     StockMenuFuncs.AskTopUp();
                     return;
                 }
                 Managers.Manager.panelM.ClearPanels();
                var p = new Panels.HSBPanel();
                Managers.Manager.panelM.AddPanel(p);
             };
            zlzj.Click += (s, e) =>
             {
                 if (!DataCenter.DataCenter.HavePermission(DataCenter.MyConst.APINames.GGYL))
                 {
                     StockMenuFuncs.AskTopUp();
                     return;
                 }
                 Managers.Manager.panelM.ClearPanels();
                var p = new Panels.GGZLZJPanel();
                Managers.Manager.panelM.AddPanel(p);
             };
            ddpx.Click += (s, e) =>
             {
                 if (!DataCenter.DataCenter.HavePermission(DataCenter.MyConst.APINames.GGYL))
                 {
                     StockMenuFuncs.AskTopUp();
                     return;
                 }
                 Managers.Manager.panelM.ClearPanels();
                var p = new Panels.DDPXPanel();
                Managers.Manager.panelM.AddPanel(p);
        };
            cje.Click += (s, e) =>
             {
                 if (!DataCenter.DataCenter.HavePermission(DataCenter.MyConst.APINames.GGYL))
                 {
                     StockMenuFuncs.AskTopUp();
                     return;
                 }
                 Managers.Manager.panelM.ClearPanels();
                var p = new Panels.CJEBPanel();
                Managers.Manager.panelM.AddPanel(p);
             };

            ggyl.DropDownItems.AddRange(new ToolStripMenuItem[] { zdb, hsl, zlzj, cje, ddpx });

            ToolStripMenuItem zsyl = new ToolStripMenuItem("指数一览");
            zsyl.Click += (sender, e) =>
            {
                if (!DataCenter.DataCenter.HavePermission(DataCenter.MyConst.APINames.ZHISHUYL))
                {
                    StockMenuFuncs.AskTopUp();
                    return;
                }
                var p = new Panels.ZhishuPanel();
                Managers.Manager.panelM.ClearPanels();
                Managers.Manager.panelM.AddPanel(p);
            };

            ToolStripMenuItem sczx = new ToolStripMenuItem();
            sczx.Text = "市场资讯";
            sczx.Click += (sender, e) =>
            {
                if (!DataCenter.DataCenter.HavePermission(DataCenter.MyConst.APINames.NEWSLIST))
                {
                    StockMenuFuncs.AskTopUp();
                    return;
                }
                Managers.Manager.newsForm.ShowForm(null);
            };

            root.DropDownItems.AddRange(new ToolStripMenuItem[] { ggyl, zsyl, sczx });
        }

        private void CreateBKPHSubitem(ToolStripMenuItem root)
        {
            ToolStripMenuItem zjh = new ToolStripMenuItem();
            ToolStripMenuItem gn = new ToolStripMenuItem();
            ToolStripMenuItem dy = new ToolStripMenuItem();
            ToolStripMenuItem sina = new ToolStripMenuItem();

            root.DropDownItems.AddRange(new ToolStripMenuItem[]{
                zjh,gn,dy});

            zjh.Text = "证监会行业";
            gn.Text = "概念板块";
            dy.Text = "地域板块";
            sina.Text = "新浪板块";

            zjh.Tag = DataCenter.Enums.BKType.zjh_bk;
            gn.Tag = DataCenter.Enums.BKType.gn_bk;
            dy.Tag = DataCenter.Enums.BKType.dy_bk;
            sina.Tag = DataCenter.Enums.BKType.sina_bk;

            zjh.Click += OnBKMenuItemClick;
            gn.Click += OnBKMenuItemClick;
            dy.Click += OnBKMenuItemClick;
            sina.Click += OnBKMenuItemClick;
        }
        

        public void InitZXGMenu()
        {
            zxgMenuItem.DropDownItems.Clear();
            foreach(var i in Managers.Manager.zxgM.zxgList)
            {
                var tmi = new ToolStripMenuItem();
                tmi.Text = i.name;
                //tmi.Tag = i.stocksArray;
                tmi.Click += (senter, e) =>
                {
                    var s = ((ToolStripMenuItem)senter);
                    if (Managers.Manager.zxgM.GetSymbols(s.Text).Length != 0)
                    {
                        Managers.Manager.panelM.ClearPanels();
                        Managers.Manager.zxgM.zxKind = s.Text;
                        var p = new Panels.GGPanel(s.Text, Managers.Manager.zxgM.GetSymbols(s.Text));
                        Managers.Manager.panelM.AddPanel(p);
                    }
                    else
                        Managers.Manager.ttsM.Speak("该分类下没有股票。");
                };
                zxgMenuItem.DropDownItems.Add(tmi);
            }
        }

        private void OnBKMenuItemClick(object sender, EventArgs e)
        {
            if (!DataCenter.DataCenter.HavePermission(DataCenter.MyConst.APINames.BKRANKING))
            {
                StockMenuFuncs.AskTopUp();
                return;
            }
            var s = (ToolStripMenuItem)sender;
            var p = new Panels.BKRankingPanel((DataCenter.Enums.BKType)s.Tag, s.Text);
            Managers.Manager.panelM.AddPanel(p);
        }

        public void Client_FormClosed(object sender, FormClosedEventArgs e)
        {
            Managers.Manager.ExitApp();
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (Managers.Manager.panelM.currentPanel != null)
                Managers.Manager.panelM.currentPanel.OnKeyDown(e);
        }

        private void dataGridView1_Leave(object sender, EventArgs e)
        {
            Managers.Manager.ttsM.Stop();
        }


        DataCenter.Models.SearchItem[] resultItems;
        string searchText;
        private void searchButton_Click(object sender, EventArgs e)
        {
            searchTextBox.Enabled = false;
            searchButton.Enabled = false;

            if (searchText != searchTextBox.Text) //本次搜索与上次不同，执行搜索
            {
                try
                {
                    resultListView.Items.Clear();
                    resultItems = DataCenter.DataCenter.Search(searchTextBox.Text);
                    if (resultItems.Length > 0)
                    {
                        foreach (DataCenter.Models.SearchItem i in resultItems)
                        {
                            if (i.type == "GP-A" || i.type == "ZS")
                            {
                                ListViewItem li = new ListViewItem(i.name);
                                li.SubItems.Add(i.code);
                                this.resultListView.Items.Add(li);
                            }
                        }
                        resultListView.Visible = true;
                        this.resultListView.Focus();
                    }
                    else
                        Managers.Manager.ttsM.Speak("没有搜索结果。");
                }
                catch (DataCenter.MyException.APINoPermissionException)
                {
                    StockMenuFuncs.AskTopUp();
                }
            }
            else
            {
                resultListView.Visible = true;
                this.resultListView.Focus();
            }

            searchTextBox.Enabled = true;
            searchButton.Enabled = true;
            searchText = searchTextBox.Text;
        }
        private void searchTextBox_TextChanged(object sender, EventArgs e)
        {
            if (searchTextBox.Text == "")
                searchButton.Enabled = false;
            else
                searchButton.Enabled = true;
        }
        private void resultListView_ItemActivate(object sender, EventArgs e)
        {
            int i = resultListView.SelectedIndices[0];
            var p = new Panels.GGPanel("搜索结果 - " + resultItems[i].name, resultItems[i].symbol);
            Managers.Manager.panelM.AddPanel(p);
            this.dataGridView1.Focus();
            this.resultListView.Visible = false;
        }
        private void searchTextBox_Enter(object sender, EventArgs e)
        {
            this.searchTextBox.SelectAll();
        }
        private void searchTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Return && this.searchTextBox.Text != "")
                searchButton_Click(null,null);

        }


        private void Client_Load(object sender, EventArgs e)
        {
            this.Text = MyConst.StaticString.APPNAME;

            Button[] ts = new Button[] { index1Button, index2Button, index3Button};
            foreach(var b in ts)
            {
                b.Click += (s2, e2) =>
                {
                    if (DataCenter.DataCenter.HavePermission("zhishuyl"))
                    {
                        var p = new Panels.ZhishuPanel();
                        Managers.Manager.panelM.AddPanel(p);
                        Managers.Manager.clientForm.dataGridView1.Focus();
                    }
                    else
                        StockMenuFuncs.AskTopUp();
                };
            }
            indexPanel.Controls.AddRange(ts);

            Managers.Manager.hotStockInfoChanged += () =>
             {
                 if (Managers.Manager.hotStockInfo == null)
                     dataGridView1.ContextMenuStrip = null;
                 else
                     dataGridView1.ContextMenuStrip = stockContextMenuStrip;
             };

            Managers.Manager.cronM.updateSuccessfully += () =>
            {
                var rs = Managers.Manager.cronM.indexStocks;
                for (int i = 0; i < rs.Length; i++)
                {
                    if (rs[i].changepercent > 0)
                        ts[i].ForeColor = Color.Red;
                    else if (rs[i].changepercent < 0)
                        ts[i].ForeColor = Color.LightGreen;
                    else
                        ts[i].ForeColor = Color.White;

                    ts[i].Text = rs[i].name + "：" + rs[i].trade + "\n上涨：" + rs[i].change + "点\n涨幅：" + rs[i].changepercent+"%";
                    ts[i].Tag = rs[i];
                }
            };
            Managers.Manager.cronM.StartCron(true);
            //zxgMenuItem.DropDownItems[0].PerformClick();
        }

        private void indexContextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            var bt = ((ContextMenuStrip)sender).SourceControl as Button;
            if (bt != null)
                Managers.Manager.hotIndex = bt.Tag as DataCenter.Models.StockInfo;
        }

        DataCenter.Models.IInfo hotInfo;
        private void stockContextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            if (Managers.Manager.hotIndex != null)
            {
                hotInfo = Managers.Manager.hotIndex;
                addZXGToolStripMenuItem.Visible = false;
                generalInfomationToolStripMenuItem.Visible = false;
            }
            else
            {
                hotInfo = Managers.Manager.hotStockInfo;

                constituentToolStripMenuItem.Visible = false;
                if (Managers.Manager.zxgM.Exist(Managers.Manager.zxgM.zxKind, Managers.Manager.hotStockInfo.symbol))
                    removeZXGToolStripMenuItem.Visible = true;
                else
                {
                    if (Managers.Manager.zxgM.zxKind != "")
                        quickAddToolStripMenuItem.Visible = true;
                }
            }


            if (Managers.Manager.panelM.currentPanel.panelName == typeof(Panels.GGKLinePanel).Name)
            {
                klineOptionToolStripMenuItem.Visible = true;
                foreach (var i in kFreqItemList)
                {
                    var tag = (string)i.Tag;
                    if (tag == Panels.GGKLinePanel.freq)
                        i.Visible = false;
                    else
                        i.Visible = true;
                }
                if (Managers.Manager.hotIndex == null)
                {
                    if (Panels.GGKLinePanel.freq.IndexOf('m') == -1 || Panels.GGKLinePanel.freq == "month")
                    {
                        fqToolStripMenuItem.Visible = true;
                        foreach (ToolStripMenuItem i in fqToolStripMenuItem.DropDown.Items)
                    {
                        var tag = (string)i.Tag;
                        if (tag == Panels.GGKLinePanel.adj)
                            i.Visible = false;
                        else
                            i.Visible = true;
                    }
                    }
                }
            }
        }
        private void stockContextMenuStrip_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            removeZXGToolStripMenuItem.Visible = false;
            quickAddToolStripMenuItem.Visible = false;
            klineOptionToolStripMenuItem.Visible = false;
            fqToolStripMenuItem.Visible = false;

            addZXGToolStripMenuItem.Visible = true;
            generalInfomationToolStripMenuItem.Visible = true;
            constituentToolStripMenuItem.Visible = true;
        }


        void KFreqItemToolStripMenuItem_click(object sender,EventArgs e)
        {
            var s = (ToolStripMenuItem)sender;
            string tag = (string)s.Tag;
            var p = new Panels.GGKLinePanel(Managers.Manager.hotStockInfo, tag);
            Managers.Manager.panelM.AddPanel(p);
            tempKFreqItem = s;
        }
        void KAdjItemToolStripMenuItem_click(object sender, EventArgs e)
        {
            var s = (ToolStripMenuItem)sender;
            string tag = (string)s.Tag;
            var p = new Panels.GGKLinePanel(Managers.Manager.hotStockInfo, Panels.GGKLinePanel.freq, tag, Panels.GGKLinePanel.start, Panels.GGKLinePanel.end);
            Managers.Manager.panelM.AddPanel(p);
            tempKAdjItem = s;
        }

        public void DisplayIndexPanel(bool display = true)
        {
            this.indexPanel.Visible = display;
        }
    }
}
